package com.pig4cloud.pig.ads.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dy.sdk.client.DyTtClient;
import com.dy.sdk.model.request.tt.TtEventsAvailableListRequest;
import com.dy.sdk.model.request.tt.TtEventsCreateRequest;
import com.dy.sdk.model.response.tt.TtResponse;
import com.google.api.client.util.Lists;
import com.pig4cloud.pig.ads.pig.mapper.AdAssetsEventMapper;
import com.pig4cloud.pig.ads.service.AdAssetsEventService;
import com.pig4cloud.pig.ads.service.TtAccesstokenService;
import com.pig4cloud.pig.api.dto.AdAvailableEventRes;
import com.pig4cloud.pig.api.entity.AdAssetsEvent;
import com.pig4cloud.pig.api.util.JsonUtil;
import com.pig4cloud.pig.api.vo.AdAssetsEventReq;
import com.pig4cloud.pig.common.core.util.R;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;
import java.util.Objects;

/**
 * 广告资产事件表
 * @author  chenxiang
 * @version  2022-04-01 16:25:19
 * table: ad_assets_event
 */
@Log4j2
@Service("adAssetsEventService")
@RequiredArgsConstructor
public class AdAssetsEventServiceImpl extends ServiceImpl<AdAssetsEventMapper, AdAssetsEvent> implements AdAssetsEventService {

	private final TtAccesstokenService ttAccesstokenService;

	/**
	 * 获取可创建事件列表
	 * @param req
	 * @return
	 */
	@Override
	public R getList(AdAssetsEventReq req){
		// 调用头条 - 获取可创建事件列表
		List<AdAvailableEventRes> adAvailableEventResList = getAvailableEvents(req.getAdvertiserId(),req.getAssetId());
		if (CollectionUtils.isNotEmpty(adAvailableEventResList)){
			// 事件回传方式列表，允许值:落地页支持:JSSDK JS埋码 、EXTERNAL_API API回传、XPATH XPath圈选应用支持：APPLICATION_API 应用API、APPLICATION_SDK 应用SDK、快应用支持：QUICK_APP_API 快应用API
			// 过滤只展示APPLICATION_SDK
			Iterator<AdAvailableEventRes> iterator = adAvailableEventResList.iterator();
			while (iterator.hasNext()){
				AdAvailableEventRes adAvailableEventRes = iterator.next();
				String trackTypes = adAvailableEventRes.getTrackTypes();
				if (!trackTypes.contains("APPLICATION_SDK")){
					iterator.remove();
				}
			}
		}
		return R.ok(adAvailableEventResList);
	}
	/**
	 * 获取资产下已经创建的事件
	 * @param req
	 * @return
	 */
	@Override
	public R getEventList(AdAssetsEventReq req){
		List<AdAssetsEvent> adAssetsEventList = this.list(Wrappers.<AdAssetsEvent>lambdaQuery().eq(AdAssetsEvent::getAssetId,req.getAssetId()).eq(AdAssetsEvent::getAdvertiserId,req.getAdvertiserId()).eq(AdAssetsEvent::getDeleted,0));
		return R.ok(adAssetsEventList);
	}
	/**
	 * 创建事件
	 * @param req
	 * @return
	 */
	@Override
	public R addEvent(AdAssetsEventReq req){
		JSONArray jsonArray = req.getEvent();
		String errorMsg = "";
		int num = 0;
		for (Object object : jsonArray){
			AdAssetsEventReq adEventReq = JSONObject.parseObject(JSON.toJSONString(object), AdAssetsEventReq.class);
			// 校验入参
			R res = this.checkParam(adEventReq);
			if (0 == res.getCode()) {
				AdAssetsEvent adAssetsEvent = new AdAssetsEvent();
				adAssetsEvent.setAdvertiserId(req.getAdvertiserId());
				adAssetsEvent.setAssetId(Long.valueOf(req.getAssetId()));
				adAssetsEvent.setEventId(Long.valueOf(adEventReq.getEventId()));
				adAssetsEvent.setEventType(adEventReq.getEventType());
				adAssetsEvent.setEventCnName(adEventReq.getEventCnName());
				// 20220526  statisticalType 已下架
//				adAssetsEvent.setStatisticalType(adEventReq.getStatisticalType());
				adAssetsEvent.setSoucreStatus(1);
				String[] trackTypes = adEventReq.getTrackTypes().split(",");
				adAssetsEvent.setTrackTypes(JSON.toJSONString(trackTypes));
				// 调用头条 - 创建事件
				R result = createEvents(adAssetsEvent, trackTypes);
				if (0 == result.getCode()) {
					this.save(adAssetsEvent);
					num++;
				} else {
					errorMsg = "，失败原因：" + result.getMsg();
				}
			}else{
				errorMsg = "，失败原因：" + res.getMsg();
			}
		}
		if (num > 0){
			return R.ok(null,"成功创建事件"+num+"个，失败"+(jsonArray.size()-num)+"个" + errorMsg);
		}else{
			return R.failed("事件创建失败" + errorMsg);
		}
	}
	/**
	 * 调用头条 - 获取可创建事件列表
	 * @param advertiserId
	 * @param assetId
	 * @return
	 */
	public List<AdAvailableEventRes> getAvailableEvents(String advertiserId, String assetId){
		List<AdAvailableEventRes> list = Lists.newArrayList();
		try {
			String accessToken = ttAccesstokenService.fetchAccesstoken(advertiserId);
			DyTtClient ttClient = new DyTtClient("");
			TtEventsAvailableListRequest eventsAvailableListRequest = new TtEventsAvailableListRequest();
			eventsAvailableListRequest.setAdvertiser_id(Long.valueOf(advertiserId));
			eventsAvailableListRequest.setAsset_id(Long.valueOf(assetId));
			log.info(">>>>>>调用头条获取可创建事件列表params：{}",JSON.toJSONString(eventsAvailableListRequest));
			String result = ttClient.call4Get(eventsAvailableListRequest, accessToken);
			log.info(">>>>>>调用头条获取可创建事件列表result：{}",result);
			TtResponse response = JSON.parseObject(result, TtResponse.class);
			if ("0".equals(response.getCode())){
				JSONObject jsonObject = response.getData();
				JSONArray jsonArray = jsonObject.getJSONArray("event_configs");
				for (Object object : jsonArray){
					JSONObject jsonObj = JsonUtil.toSnakeObject(JSON.toJSONString(object), JSONObject.class);
					AdAvailableEventRes adAvailableEventRes = JSON.toJavaObject(jsonObj, AdAvailableEventRes.class);
					adAvailableEventRes.setAdvertiserId(advertiserId);
					adAvailableEventRes.setAssetId(Long.valueOf(assetId));
					list.add(adAvailableEventRes);
				}
			}else{
				log.error(">>>>>>调用头条获取可创建事件列表异常：{}",response.getMessage());
			}
		} catch (Exception e) {
			log.error(">>>>>>调用头条获取可创建事件列表异常：{}",e.getMessage());
		}
		return list;
	}

	/**
	 * 调用头条 - 创建事件
	 * @param adAssetsEvent
	 * @return
	 */
	public R createEvents(AdAssetsEvent adAssetsEvent, String[] trackTypes){
		try {
			String advertiserId = adAssetsEvent.getAdvertiserId();
			String accessToken = ttAccesstokenService.fetchAccesstoken(advertiserId);
			DyTtClient ttClient = new DyTtClient("");
			TtEventsCreateRequest eventsCreateRequest = new TtEventsCreateRequest();
			eventsCreateRequest.setAdvertiser_id(Long.valueOf(advertiserId));
			eventsCreateRequest.setAsset_id(adAssetsEvent.getAssetId());
			eventsCreateRequest.setAsset_type("APP");
			eventsCreateRequest.setEvent_id(adAssetsEvent.getEventId());
//			eventsCreateRequest.setStatistical_type(adAssetsEvent.getStatisticalType());
			eventsCreateRequest.setTrack_types(trackTypes);
			log.info(">>>>>>调用头条创建事件params：{}",JSON.toJSONString(eventsCreateRequest));
			String result = ttClient.call4Post(eventsCreateRequest, accessToken);
			log.info(">>>>>>调用头条创建事件result：{}",result);
			TtResponse response = JSON.parseObject(result, TtResponse.class);
			if ("0".equals(response.getCode())){
				return R.ok();
			}else{
				log.error(">>>>>>调用头条创建事件异常：{}",response.getMessage());
				return R.failed(response.getMessage());
			}
		} catch (Exception e) {
			log.error(">>>>>>调用头条创建事件异常：{}",e.getMessage());
		}
		return R.failed();
	}
	/**
	 * 校验入参
	 * @param req
	 * @return
	 */
	private R checkParam(AdAssetsEventReq req){
		if (StringUtils.isBlank(req.getEventId())){
			return R.failed("未获取到事件ID");
		}
		if (StringUtils.isBlank(req.getEventType())){
			return R.failed("未获取到事件类型");
		}
		if (StringUtils.isBlank(req.getEventCnName())){
			return R.failed("未获取到事件名称");
		}
//		if (StringUtils.isBlank(req.getStatisticalType())){
//			return R.failed("未获取到统计方式");
//		}
		if (StringUtils.isBlank(req.getTrackTypes())){
			return R.failed("未获取到事件回传方式");
		}
		return R.ok();
	}
}


